var app = require('../app'),
    template = require('../../modules/template'),
    formMod = require('../../modules/form');

// 判断 字符串是否以特定字符结尾
String.prototype.endWith = function(endStr){
    var d = this.length - endStr.length;
    return (d >= 0 && this.lastIndexOf(endStr) == d);
}

var singleFile = true;   // 如果只允许上传一个文件，这个值为 true 

var r = new Uploader({
    target: '/casepublic/chunk',
    singleFile: singleFile,
    chunkSize: 2 * 1024 * 1024,           // 分片大小 2Mb 
    testChunks: true,
    headers: {
        "X-Requested-With": "XMLHttpRequest"
    },
    simultaneousUploads: 1,
    forceChunkSize: true,
    checkChunkUploadedByResponse: function (chunk, message) {
        // console.log(chunk, message);
        var objMessage = {}
        try {
            objMessage = JSON.parse(message).data;
        } catch (e) { }
        // fake response
        // objMessage.uploaded_chunks = [2, 3, 4, 5, 6, 8, 10, 11, 12, 13, 17, 20, 21]
        // check the chunk is uploaded
        return (objMessage.uploaded_chunks || []).indexOf(chunk.offset + 1) >= 0
    },
    processResponse: function(response, cb){
        response = JSON.parse(response);

        if(response.code == 201 || response.code == 200){
            cb(null, response);
        }else if(response.code){
            toastr.error(response.message);
            $('#fileProgress').html(""); 
        }else{
            toastr.error(response);
            $('#fileProgress').html(""); 
        }
    }
});

// 如果不支持，就提示他换浏览器
if (!r.support) {
    alert("您使用的浏览器不支持文件上传，请使用最新的 chrome 或者 火狐浏览器");
    return;
}else{
    // 上传文件的拖拽区域和按钮
    $('.uploader-drop').show();
    r.assignDrop($('.uploader-drop')[0]);
    r.assignBrowse($('.uploader-browse')[0], false, true, { accept: '.zip, .rar' });

    
    // r.assignBrowse($('.uploader-browse-folder')[0], true);
    // r.assignBrowse($('.uploader-browse-image')[0], false, false, { accept: 'image/*' });
    
    r.on('dragover', function (e) {
        $('.uploader-drop').addClass("droping");
    })
    r.on('dragleave', function (e) {
        $('.uploader-drop').removeClass("droping");
    })

    // Handle file add event
    r.on('filesAdded', function (files, fileList) {     // 添加单个文件
        
        $('.uploader-drop').removeClass("droping");
        
        fileList.forEach(function (file) {
            
            if(!file.name.endWith(".zip") && !file.name.endWith(".rar")){
                toastr.warning('请上传 .zip 或 .rar 文件');
                return;
            }

            // 单个文件上传的 dom
            var $self = file.$el = $(
                '<div class="progress">' +
                    '<div class="progress-bar progress-bar-success" style="width: 0%;"></div>' +
                    '<div class="progress-info">' +
                        '<p class="file-name col-lg-3 col-md-3 col-sm-3 col-xs-2"></p>' +
                        '<p class="file-md5 col-lg-2 col-md-2 col-sm-2 col-xs-2"></p>' +
                        '<p class="file-size col-lg-2 col-md-2 col-sm-2 col-xs-2"></p>' +
                        '<p class="file-state col-lg-3 col-md-3 col-sm-2 col-xs-2">' +
                            '<span class="file-persent"></span>' +
                            '<span class="file-speed"></span>' +
                            '<span class="file-time"></span>' +
                        '</p>' +
                        '<p class="file-operation col-lg-2 col-md-2 col-sm-3 col-xs-4">' +
                            '<span class="file-icon file-pause glyphicon glyphicon-pause"></span>' +
                            '<span class="file-icon file-resume glyphicon glyphicon-play"></span>' +
                            '<span class="file-icon file-cancel glyphicon glyphicon-remove"></span>' +
                            '<span class="file-icon file-ok glyphicon glyphicon-ok"></span>' +
                        '</p>' +
                    '</div>' +
                '</div>'
            );
            
            $self.find('.file-name').text(file.name);  // 文件名
            $self.find('.file-size').text(file.getFormatSize());   // 文件大小
            
            // 暂停
            $self.find('.file-pause').on('click', function () {
                file.pause();   // 暂停 file 上传
                
                // 展示改变
                $self.find('.file-pause').hide(); 
                $self.find('.file-resume').show();
            });
            
            // 重新开始
            $self.find('.file-resume').on('click', function () {
                file.resume();      // 重新开始 上传
                
                // 展示改变
                $self.find('.file-pause').show();
                $self.find('.file-resume').hide();
            });
            
            // 取消
            $self.find('.file-cancel').on('click', function () {
                file.cancel();      // 取消上传
                $self.remove();     // 删除 DOM
            });
            
            // 单文件上传  就覆盖掉
            if(singleFile){
                $('#fileProgress').html($self); 
            }else{
                $('#fileProgress').append($self);
            }
            
            computeMD5(file);

            $("#identifier").val("");
        });
    });
        
    // 和 filesAdded 类似，但是是文件已经加入到上传列表中，一般用来开始整个的上传
    r.on('filesSubmitted', function (files, fileList) {
        // window.r.upload();
    });
    
    // 已经开始上传了
    r.on('uploadStart', function () {
        // 展示暂停，隐藏开始
        // 原来的总进度条
        // $('.uploader-progress .progress-resume-link').hide();
        // $('.uploader-progress .progress-pause-link').show();
    });
    
    // 一个文件在上传中
    r.on('fileProgress', function (rootFile, file) {
        
        var $self = rootFile.$el,
            progress = Math.floor(rootFile.progress() * 100);

        $self.find(".file-persent").html(progress + '%');
        $self.find(".file-speed").html(Uploader.utils.formatSize(rootFile.averageSpeed) + '/s');
        $self.find(".file-time").html(secondsToStr(rootFile.timeRemaining()));
        $self.find(".progress-bar").css({ width: progress + '%' });

    });
    
    // 一个根文件（文件夹）成功上传完成
    r.on('fileComplete', function (rooFile) {
        var $self = rooFile.$el
        $self.find('.file-ok').show().css("color", "#fff");
        $self.find('.file-pause, .file-resume, .file-cancel').remove();

        $("#identifier").val(rooFile.uniqueIdentifier);

    });
    
    // 上传完毕
    r.on('complete', function () {
        // 当文件上传完成时 隐藏 开始、暂停 按钮
        $('.uploader-progress .progress-resume-link, .uploader-progress .progress-pause-link').hide();
    });
    
    // 上传过程中出错了
    r.on('fileError', function (rootFile, file, message) {
        var $self = rootFile.$el;

        $self.addClass("danger");
        $self.find(".file-md5").html("呀，出错了");
        $self.find('.file-pause, .file-resume').remove();
    });
    
    // 所有的事件
    r.on('catchAll', function () {
        // console.log.apply(console, arguments);
    });
    
    window.r = {
        pause: function () {
            r.pause();
            // Show resume, hide pause
            $('.file-resume').show();
            $('.file-pause').hide();
        },
        cancel: function () {
            r.cancel();
            $('.progress').remove();
        },
        upload: function () {
            $('.file-pause').show();
            $('.file-resume').hide();
            r.resume();
        },
        uploader: r
    };
}
    
// 秒换算成  天/时/分/秒
function secondsToStr(temp) {
    var timeStr = "",
    
    dayBase = 24 * 60 * 60 ,
    hourBase = 60 * 60 ,
    minuteBase = 60 ,
    secondBase = 1,
    
    day = Math.floor(temp / dayBase),
    hour = Math.floor(temp % dayBase / hourBase),
    minute = Math.floor(temp % dayBase % hourBase / minuteBase),
    second = Math.floor(temp % dayBase % hourBase % minuteBase / secondBase);
    
    timeStr = (day ? day + "天 " : "")
    + (hour ? hour + "时 " : "")
    + (minute ? minute + "分 " : "")
    + (second ? second + "秒 " : "");
    
    timeStr = timeStr ? timeStr : "";
    if(timeStr.indexOf("Infinity") >= 0){
        timeStr = "计算中..." 
    }
    return timeStr;
}

// 计算MD5值
function computeMD5(file) {
    var $self = file.$el;

    var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
        chunkSize = 2097152, // 单块 2MB
        chunks = Math.ceil(file.size / chunkSize),
        currentChunk = 0,
        spark = new SparkMD5.ArrayBuffer(),
        frOnload = function(e){

            // 已经计算的比例
            $self.find(".file-md5").html("MD5校验进度 " + Math.floor((currentChunk / chunks) * 100) + "%");

            spark.append(e.target.result); // append array buffer
            currentChunk++;
            if (currentChunk < chunks){
                loadNext();
            }
            else{
                $self.find(".file-md5").html("MD5校验，已完成");
                file.uniqueIdentifier = spark.end();

                $self.find('.file-pause,.file-cancel').show();
                $self.find('.file-resume').hide();
                file.resume();
            }
        },
        frOnerror = function () {
            $self.find(".file-md5").html("抱歉，文件读取出错了");
        };
    function loadNext() {
        var fileReader = new FileReader();
        fileReader.onload = frOnload;
        fileReader.onerror = frOnerror;
        var start = currentChunk * chunkSize,
            end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
        fileReader.readAsArrayBuffer(blobSlice.call(file.file, start, end));
    };

    loadNext();
}

function linkage(el){
    var thisValue = el.val(),
    formHide = $(".form-hide");

    if(thisValue.length){
        formHide.slideDown("fast");
    }else{
        formHide.slideUp("fast");
        $("#plaintiff_name, #template_name, #agent_name").val("");
        return;
    }
    $.ajax({
        url: "/casepublic/getInfo",
        type: "post",
        data: {
            plaintiff_id: thisValue
        },
        dataType: "json",
        success: function(res){
            if(res.code == 200){
                var templateElments = template.render("options", {data: res.data.template}),
                    agentElments = template.render("options", {data: res.data.agent});
                
                $("#template_id").val("").html(templateElments);
                $("#agent_id").val("").html(agentElments);
            }else{
                toastr.error(res.message);
            }
        },
        error: function(){
            toastr.error("网络错误，请稍候再试");
        }
    });
}

linkage($("#plaintiff_id"));

$("body")
    .on("change", "#plaintiff_id", function(){
        linkage($(this));
    })
    .on("click", "#reset", function(){
        $(".progress").remove();
        $("#identifier").val("");
        $(".form-hide").slideUp("fast");
        $("#plaintiff_name, #template_name, #agent_name").val("");
    })
    .on("change", "#plaintiff_id", function(){
        var thisText = $(this).find("option:selected").text();
        $("#plaintiff_name").val(thisText);
    })
    .on("change", "#template_id", function(){
        var thisText = $(this).find("option:selected").text();
        $("#template_name").val(thisText);
    })
    .on("change", "#agent_id", function(){
        var thisText = $(this).find("option:selected").text();
        $("#agent_name").val(thisText);
    });



// 表单验证
formMod.listen("/caseentry/saveinfo",{
    ajaxBefore: function(){
        
    },
    // validSuccess: function(){
    //     $("#submitBtn").removeAttr("disabled");
    // },
    // validError: function(){
    //     $("#submitBtn").attr("disabled");
    // },
    //验证错误
    validError:function(validResutl){

        var item = validResutl.element,
            item_span = item.parents('.form-group').find('.error-tips');

        if(item.attr('name')=='plaintiff_id'){
            if(validResutl.valid == 'notempty'){
                item_span.html('请选择原告方');
            }
        }
        if(item.attr('name')=='case_type'){
            if(validResutl.valid == 'notempty'){
                item_span.html('请选择案件类型');
            }
        }
        if(item.attr('name')=='template_id'){
            if(validResutl.valid == 'notempty'){
                item_span.html('请选择案件模板');
            }
        }
        if(item.attr('name')=='agent_id'){
            if(validResutl.valid == 'notempty'){
                item_span.html('请选择代理人');
            }
        }
        if(item.attr('name')=='identifier'){
            if(validResutl.valid == 'notempty'){
                toastr.warning('请上传案件资料');
            }
        }
    },
    //操作中清除提示
    cleanup:function(item){
        $('.error-tips').html("");
    },
    success:function(result){
        console.log(result);
        var res = result.data;
        if(res.code == 200){
            toastr.success('提交数据成功，正在去往录入记录页...');

            setTimeout(function(){
                window.location.href = "/caseentry/list";
            }, 3000);

            // 回到首页
            // setTimeout(function(){
            //     window.location.href("/");
            // }, 3000);
        }else{
            toastr.error(res.message);
        }
    },
    error:function(){
        toastr.error("网络错误，请稍候再试");
    }
});

